package com.book.bigwork.DetailsService;

import com.book.bigwork.model.User;
import com.book.bigwork.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;

    @Autowired
    public UserDetailsServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findOneWithRolesByUserName(username);
        if (user == null) {
            System.out.print("error happen and user is null:" + "\n");
            throw new UsernameNotFoundException(username);
        }
        List<GrantedAuthority> roles = user.getRoles().stream()
                .map(authority -> new SimpleGrantedAuthority(authority.
                        getRoleName()))
                .collect(Collectors.toList());
        return new org.springframework.security.core.userdetails.User
                (user.getUserName(), user.getUserPassword(), roles);
    }
}
